﻿using Adp;
using Adp.Common;
using Microsoft.AspNetCore.Mvc;
using Yqd.Core;
using Yqd.Enm;
using Yqd.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace Yqd.Controllers
{
    public class DepartmentController : BaseController
    {
        YqdContext ctx;
        DdService ddService;
        static string UnitCode = "";
        static string UnitName = "";

        public DepartmentController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        public ActionResult GetList()
        {
            var ParentCode = Form.GetString("ParentCode");
            var Paths = Form.GetString("Paths");
            var Fullname = Form.GetString("Fullname");

            var key = Form.GetString("key");
            //var r = ctx.Yqd_Department.AsQueryable();
            //r = r.Where(it => it.ParentCode == ParentCode || it.Name.ToLower().Trim().Contains(key.ToLower().Trim()));
            string sql = "";
            if (key.Trim() != "")
            {
                sql = " or name like '%" + key.ToLower().Trim() + "%'";
            }
            var r = ctx.Database.SqlQuery<Yqd_Department>($"select * From Yqd_Department where ParentCode='{ParentCode}'{sql}");

            return this.ToJson(new
            {
                success = true,
                data = r.Select(it => new
                {
                    ID = it.OrganizationCode,
                    it.OrganizationCode,
                    label = it.Name,
                    it.isLeaf,
                    Paths = (Paths + "." + it.OrganizationCode).Trim('.'),
                    Fullname = (Fullname + ">" + it.Name).Trim('>')
                })
            });
        }

        public ActionResult GetUnitList()
        {
            var start = Form.GetInt("start");
            var limit = Form.GetInt("limit");
            var key = Form.GetString("key");
            var unbind = Form.GetBool("unbind", false);
            var where = "[UnitCode]!='330782000000'";
            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([Name]))) like {0}";
            }
            if (unbind)
            {
                where += " and (OrganizationCode is null or OrganizationCode='')";
            }
            var (totalcount, data) = ctx.Database.SqlPager<Yqd_Unit>(start, limit, "*", where, "[Tactic] asc", "%" + key.ToLower().Trim() + "%");
            var ds = ctx.Yqd_Department.Where(it => it.TypeCode == "GOV_UNIT").Select(it => new { it.OrganizationCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = data.Select(q => new
                {
                    q.ID,
                    Dept = q.Name,
                    q.OrganizationCode,
                    Name = ds.FirstOrDefault(it => it.OrganizationCode == q.OrganizationCode)?.Name ?? ""
                })
            });
        }


        public ActionResult GetUnitList2()
        {
            var r = ctx.Yqd_Unit;
            return this.ToJson(new
            {
                success = true,
                data = r.Select(it => new
                {
                    value = it.UnitCode,
                    name = it.Name
                })
            });
        }

        public ActionResult GetLeaderList() {
            var start = Form.GetInt("start");
            var limit = Form.GetInt("limit");
            var key = Form.GetString("key");
            var unbind = Form.GetBool("unbind", false);
            var where = "[UnitCode]!='330782000000'";
            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([Name]))) like {0}";
            }
            if (unbind)
            {
                where += " and (OrganizationCode is null or OrganizationCode='')";
            }
            var (totalcount, data) = ctx.Database.SqlPager<Yqd_Unit>(start, limit, "*", where, "[Tactic] asc", "%" + key.ToLower().Trim() + "%");
            var ds = ctx.Yqd_Department.Where(it => it.TypeCode == "GOV_UNIT").Select(it => new { it.OrganizationCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = data.Select(q => new
                {
                    q.ID,
                    Dept = q.Name,
                    q.OrganizationCode,
                    Name = ds.FirstOrDefault(it => it.OrganizationCode == q.OrganizationCode)?.Name ?? ""
                })
            });
        }

        public ActionResult GetDeptList()
        {
            var key = Form.GetString("key");
            var r = ctx.Yqd_Department.Where(it => it.TypeCode == "GOV_UNIT");
            if (key.Trim() != "")
            {
                r = r.Where(it => it.Name.ToLower().Trim().Contains(key.ToLower().Trim()));
            }
            return this.ToJson(new
            {
                success = true,
                data = r.Select(it => new
                {
                    ID = it.OrganizationCode,
                    label = it.Name,
                    isLeaf = it.isLeaf,
                    Paths = it.OrganizationCode.ToString()
                })
            });
        }

        public ActionResult GetUserList()
        {
            var PageNo = Form.GetInt("start");
            var PageSize = Form.GetInt("limit");
            var OrganizationCode = Form.GetString("OrganizationCode");
            var Fullname = Form.GetString("Fullname");

            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var arr = ddService.pageOrganizationEmployeePositions(OrganizationCode, config.TenantId);
            var r = new List<dynamic>();
            var dept = ctx.Yqd_Department.Select(it => new { it.OrganizationCode, it.Name }).ToList();
            if (arr != null)
            {
                foreach (var j in arr)
                {
                    var o = JToken.Parse(j.ToString());
                    if (o["govEmployeePositions"][0]["status"].ToString() == "F")
                    {
                        continue;
                    }
                    var unitCode = o["govEmployeePositions"][0]["empPosUnitCode"]?.ToString();
                    o["empJobLevelName"] = ddService.GetPropertyNameByCode("职级", o["empJobLevelCode"]?.ToString());
                    o["Role"] = 角色类型.未设置.ToString();
                    o["Permit"] = "未设置";
                    o["Status"] = 0;
                    o["OrganizationCode"] = OrganizationCode;
                    o["OrganizationName"] = Fullname;
                    o["IsUpdateUnit"] = 0;
                    var eu = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == o["employeeCode"].ToString());
                    if (eu != null)
                    {
                        o["IsUpdateUnit"] = eu.IsUpdateUnit;
                        if (eu.IsUpdateUnit == 1)
                        {
                            o["UnitCode"] = GetFullName(eu.UnitCode);
                        }
                        else {
                            o["UnitCode"] = dept.FirstOrDefault(it => it.OrganizationCode == eu.UnitCode)?.Name;
                        }
                        o["Status"] = (int)eu.Status;
                        if (eu.Roles.Length > 0)
                            o["Role"] = string.Join(',', eu.Roles.Split(",").Select(it => (角色类型)int.Parse(it)));
                        if (eu.PermitItem.Length > 0)
                            o["Permit"] = string.Join(',', eu.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it)));

                        o["RoleCode"] = !string.IsNullOrWhiteSpace(eu.Roles) ? JToken.Parse(JsonConvert.SerializeObject(eu.Roles.Split(",").Select(it => int.Parse(it)).ToList())) : JToken.Parse(JsonConvert.SerializeObject(new List<int>()));
                        o["PermitCode"] = !string.IsNullOrWhiteSpace(eu.PermitItem) ? JToken.Parse(JsonConvert.SerializeObject(eu.PermitItem.Split(",").Select(it => int.Parse(it)))) : JToken.Parse(JsonConvert.SerializeObject(new List<int>()));
                        o["IsUpdateUnit"] = eu.IsUpdateUnit;
                    }
                    o["posOrder"] = o["govEmployeePositions"][0]["orderInOrganization"]?.ToString();
                    o["gmtCreate"] = Convert.ToDateTime(o["gmtCreate"].ToString());
                    o["empGender"] = Convert.ToInt32(o["empGender"].ToString());
                    r.Add(o);
                }
            }
            //var x = JsonConvert.SerializeObject(r.OrderBy(it => it.posOrder).ThenBy(it => it.empGender).ThenBy(it => it.gmtCreate).Skip((PageNo - 1) * PageSize).Take(PageSize));
            return this.ToJson(new
            {
                success = true,
                totalcount = r.Count,
                data = r.OrderBy(it => Convert.ToInt32(it.posOrder)).ThenBy(it => it.empGender).ThenBy(it => it.gmtCreate).Skip((PageNo - 1) * PageSize).Take(PageSize)
            });
        }
        public ActionResult SearchUserList()
        {

            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            //var result2 = this.ddService.pageSearchEmployee(1, 100, "何文飞", config.TenantId);
            //var result3 = this.ddService.listEmployeePositionsByEmployeeCode("GO_cf00980521ff42e395c572ec93f5bfd5", config.TenantId);
            //var result1 = this.ddService.GetOrganizationInfo("GO_cf00980521ff42e395c572ec93f5bfd5", config.TenantId);
            //GO_e17078be34b34b1e9137982aac2668f0
            var PageNo = Form.GetInt("start");
            var PageSize = Form.GetInt("limit");
            var OrgCode = Form.GetString("OrganizationCode");
            var level = Form.GetInt("Level", 1);
            var key = Form.GetString("key");
            var role = Form.GetInt("role", -1);
            var permit = Form.GetInt("permit", -1);
            var isUpdateUnit = Form.GetString("isUpdateUnit");
            var where = "1=1 and orderInOrganization is not null and isdelete=0 and status=1 ";
            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([Name]))) like {0}";
            }
            if (OrgCode.Trim() != "" && level > 1)
            {
                var code = level < 4 ? "[UnitCode]" : "[OrganizationCode]";
                where += " and " + code + "= {3}";
            }
            if (role > -1)
            {
                where += " and (','+[Roles]+',') like {1}";
            }
            if (permit > -1)
            {
                where += " and (','+[PermitItem]+',') like {2}";
            }
            if (!string.IsNullOrEmpty(isUpdateUnit))
            {
                where += " and IsUpdateUnit=" + isUpdateUnit;
            }
            var (totalcount, data) = ctx.Database.SqlPager<Yqd_User>((PageNo - 1) * PageSize, PageSize, "*", where, "Convert(bigint,orderInOrganization) asc,gender asc,gmtCreate asc", "%" + key.ToLower().Trim() + "%", "%," + role + ",%", "%," + permit + ",%", OrgCode);
            var dept = ctx.Yqd_Department.Select(it => new { it.OrganizationCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = data.Select(q => new
                {
                    employeeName = q.Name,
                    employeeCode = q.EmployeeCode,
                    q.empJobLevelCode,
                    q.empBudgetedPostCode,
                    q.empJobLevelName,
                    Role = !string.IsNullOrWhiteSpace(q.Roles) ? string.Join(',', q.Roles.Split(",").Select(it => (角色类型)int.Parse(it))) : "",
                    RoleCode = !string.IsNullOrWhiteSpace(q.Roles) ? q.Roles.Split(",").Select(it => int.Parse(it)).ToList() : new List<int>(),
                    Permit = !string.IsNullOrWhiteSpace(q.PermitItem) ? string.Join(',', q.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it))) : "",
                    PermitCode = !string.IsNullOrWhiteSpace(q.PermitItem) ? q.PermitItem.Split(",").Select(it => int.Parse(it)) : new List<int>(),
                    q.Status,
                    posOrder=q.orderInOrganization,
                    UnitCode = q.IsUpdateUnit == 1 ? GetFullName(q.UnitCode) : dept.FirstOrDefault(it => it.OrganizationCode == q.UnitCode)?.Name,
                    q.OrganizationCode,
                    q.OrganizationName,
                    q.IsUpdateUnit,
                    q.RealtionEmployeeCode
                })
            });
        }
        //private string GetFullName(string OrganizationCode)
        //{
        //    var ctx = Fn.GetService<YqdContext>();
        //    List<string> list = new List<string>();
        //    var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
        //    if (org == null)
        //    {
        //        return "";
        //    }
        //    list.Add(org.Name);
        //    var result = GetParentName(list, org.ParentCode);
        //    result.Reverse();
        //    return string.Join(">", result);
        //}
        public ActionResult GetUserList1()
        {
            var OrganizationCode = Form.GetString("OrganizationCode");
            return this.ToJson(new
            {
                success = true,
                data = ctx.Yqd_User.Where(it => it.OrganizationCode == OrganizationCode).Select(it => new
                {
                    it.empBudgetedPostCode,
                    it.Name,
                    it.empJobLevelName,
                    Role = it.Roles
                })
            });
        }

        public ActionResult GetLogList()
        {
            var start = Form.GetInt("start");
            var limit = Form.GetInt("limit");
            var key = Form.GetString("key");
            var sdate = Form.GetDateTime("sdate", DateTime.MinValue);
            var edate = Form.GetDateTime("edate", DateTime.MinValue);
            var r = ctx.Yqd_Logging.AsQueryable();
            var user = ctx.Yqd_User.ToList();
            if (key.HasValue())
            {
                var codes = user.Where(it => it.Name.Trim().Contains(key.Trim()) || it.OrganizationName.Trim().Contains(key.Trim())).Select(it => it.EmployeeCode).ToArray();
                r = r.Where(it => codes.Contains(it.EmployeeCode));
            }
            if (sdate != DateTime.MinValue)
            {
                r = r.Where(it => it.Instime > sdate);
            }
            if (edate != DateTime.MinValue)
            {
                var ed = edate.AddDays(1);
                r = r.Where(it => it.Instime < ed);
            }
            Yqd_User su = null;
            return this.ToJson(new
            {
                success = true,
                totalcount = r.Count(),
                data = r.OrderByDescending(it => it.Instime).Skip(start).Take(limit).ToList().Select(q => new
                {
                    employeeName = (su = user.FirstOrDefault(it => it.EmployeeCode == q.EmployeeCode)).Name,
                    employeeCode = q.EmployeeCode,
                    su.empJobLevelName,
                    Role = !string.IsNullOrWhiteSpace(su.Roles) ? string.Join(',', su.Roles.Split(",").Select(it => (角色类型)int.Parse(it))) : "",
                    Permit = !string.IsNullOrWhiteSpace(su.PermitItem) ? string.Join(',', su.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it))) : "",
                    su.OrganizationName,
                    Instime = q.Instime.ToString("yyyy-MM-dd HH:mm:ss")
                })
            });
        }

        private string GetFullName(string OrganizationCode)
        {
            List<string> list = new List<string>();
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
            if (org == null)
            {
                return "";
            }
            list.Add(org.Name);
            var result = GetParentName(list, org.ParentCode);
            result.Reverse();
            return string.Join(">", result);
        }
        private List<string> GetParentName(List<string> str, string parentOrganizationCode)
        {
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == parentOrganizationCode);
            if (org == null)
            {
                return str;
            }
            str.Add(org.Name);

            return GetParentName(str, org.ParentCode);
        }
        public ActionResult UpdateUser()
        {
            var employees = Form.GetStringArray("Employees[]");
            var organizationCode = Form.GetString("OrganizationCode");

            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            if (employees.Any())
            {
                var user = ctx.Yqd_User.Where(it => employees.Contains(it.EmployeeCode)).ToList();

                foreach (var item in user)
                {
                    var info = ddService.listEmployeePositionsByEmployeeCode(item.EmployeeCode, config.TenantId);
                    var organizationCode1 = info["data"][0]["organizationCode"].ToString();
                    var fullname = GetFullName(organizationCode1);
                    item.OrganizationCode = organizationCode1;
                    item.OrganizationName = fullname;
                    item.orderInOrganization = info["data"][0]["orderInOrganization"]?.ToString();
                    var unit = GetUnit(info["data"][0]["empPosUnitCode"]?.ToString());
                    item.UnitCode = unit.UnitCode;
                    item.UnitName = unit.UnitName;
                    ctx.SaveChanges();
                }
            }
            else
            {
                var result = ddService.pageOrganizationEmployeePositions(organizationCode, config.TenantId);
                foreach (var o in result)
                {
                    var info = JToken.Parse(o.ToString());

                    var OrganizationCode = info["govEmployeePositions"][0]["organizationCode"]?.ToString();
                    //var info = ddService.GetEmployeeInfo(item, config.TenantId);
                    var employeeCode = info["employeeCode"]?.ToString();

                    var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == employeeCode);
                    var empJobLevelCode = info["empJobLevelCode"]?.ToString() ?? "";
                    var empBudgetedPostCode = info["empBudgetedPostCode"]?.ToString() ?? "";
                    var unit = GetUnit(OrganizationCode);
                    var fullname = GetFullName(unit.UnitCode);
                    if (emp == null)
                    {
                        emp = new Yqd_User
                        {
                            AccountId = 0,
                            Openid = "",
                            Roles = "30",
                            PermitItem = "0",
                            EmployeeCode = employeeCode,
                            Name = info["employeeName"].ToString(),
                            Avatar = info["govEmpAvatar"]?.ToString() ?? "",
                            Gender = info["empGender"].ToString().ToInt(),
                            OrganizationCode = OrganizationCode,
                            OrganizationName = fullname,
                            UnitCode = unit.UnitCode,
                            UnitName = unit.UnitName,
                            empJobLevelCode = empJobLevelCode,
                            orderInOrganization = info["govEmployeePositions"][0]["orderInOrganization"]?.ToString(),
                            empBudgetedPostCode = empBudgetedPostCode,
                            empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode),
                            empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode),
                            gmtCreate = Convert.ToDateTime(info["gmtCreate"].ToString()),
                            Status = info["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中,
                            Instime = DateTime.Now
                        };
                        if (emp.AccountId == 0)
                        {
                            var AccountId = ddService.listEmployeeAccountIds(emp.EmployeeCode, config.TenantId);
                            if (AccountId?["accountId"] != null)
                            {
                                emp.AccountId = AccountId["accountId"].ToString().ToInt();
                            }
                        }
                        ctx.Yqd_User.Add(emp);
                    }
                    else
                    {
                        emp.Name = info["employeeName"].ToString();
                        if (info["govEmpAvatar"] != null)
                        {
                            emp.Avatar = info["govEmpAvatar"].ToString();
                        }
                        if (info["empGender"] != null)
                        {
                            emp.Gender = info["empGender"].ToString().ToInt();
                        }
                        emp.OrganizationCode = OrganizationCode;
                        emp.OrganizationName = fullname;
                        emp.empJobLevelCode = empJobLevelCode;
                        emp.UnitCode = unit.UnitCode;
                        emp.UnitName = unit.UnitName;
                        emp.empBudgetedPostCode = empBudgetedPostCode;
                        emp.empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode);
                        emp.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode);
                        emp.orderInOrganization = info["govEmployeePositions"][0]["orderInOrganization"]?.ToString();
                        emp.Instime = DateTime.Now;

                        var Status = info["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中;
                        if(Status == 用户状态.使用中)
                        {
                            emp.isDelete = 0;
                        }
                    }
                }
            }
            //var str = users.ToString().TrimEnd(',');
            //var xx = str.Split(',').ToList();
            //var us = ctx.Yqd_User.Where(x => x.OrganizationCode == orgCode && !xx.Contains(x.EmployeeCode)).ToList();
            //foreach (var item in us)
            //{
            //    item.Status = 用户状态.已停用;
            //}
            //var arr = ddService.pageOrganizationEmployeeCodes(orgCode, config.TenantId);
            //var r = new ArrayList();
            //foreach (var item in arr)
            //{
            //    var info = ddService.GetEmployeeInfo(item, config.TenantId);
            //    var employeeCode = info["employeeCode"]?.ToString();
            //    var OrganizationCode = info["OrganizationCode"]?.ToString();
            //    var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == employeeCode);
            //    var empJobLevelCode = info["empJobLevelCode"]?.ToString() ?? "";
            //    var empBudgetedPostCode = info["empBudgetedPostCode"]?.ToString() ?? "";
            //    var unit = GetUnit(OrganizationCode);
            //    var fullname = GetFullName(unit.UnitCode);
            //    if (emp == null)
            //    {
            //        emp = new Yqd_User
            //        {
            //            AccountId = 0,
            //            Openid = "",
            //            Roles = "30",
            //            PermitItem =  "0",
            //            EmployeeCode = employeeCode,
            //            Name = info["employeeName"].ToString(),
            //            Avatar = info["govEmpAvatar"]?.ToString() ?? "",
            //            Gender = info["empGender"].ToString().ToInt(),
            //            OrganizationCode = OrganizationCode,
            //            OrganizationName = fullname,
            //            UnitCode = unit.UnitCode,
            //            UnitName = unit.UnitName,
            //            empJobLevelCode = empJobLevelCode,
            //            empBudgetedPostCode = empBudgetedPostCode,
            //            empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode),
            //            empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode),
            //            Status = 用户状态.使用中,
            //            Instime = DateTime.Now
            //        };
            //        ctx.Yqd_User.Add(emp);
            //    }
            //    else
            //    {
            //        emp.Name = info["employeeName"].ToString();
            //        if (info["govEmpAvatar"] != null)
            //        {
            //            emp.Avatar = info["govEmpAvatar"].ToString();
            //        }
            //        if (info["empGender"] != null)
            //        {
            //            emp.Gender = info["empGender"].ToString().ToInt();
            //        }
            //        emp.OrganizationCode = OrganizationCode;
            //        emp.OrganizationName = fullname;
            //        emp.empJobLevelCode = empJobLevelCode;
            //        emp.UnitCode = unit.UnitCode;
            //        emp.UnitName = unit.UnitName;
            //        emp.empBudgetedPostCode = empBudgetedPostCode;
            //        emp.empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode);
            //        emp.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode);
            //        emp.Instime = DateTime.Now;
            //    }
            //    if (emp.AccountId == 0)
            //    {
            //        var AccountId = ddService.listEmployeeAccountIds(emp.EmployeeCode, config.TenantId);
            //        if (AccountId?["accountId"] != null)
            //        {
            //            emp.AccountId = AccountId["accountId"].ToString().ToInt();
            //        }
            //    }
            //}
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult SetRole()
        {
            var Employees = Form.GetString("Employees").ToJArray();
            var Role = Form.GetString("Role");
            var relationEmployeeCode = Form.GetString("relationEmployeeCode");
            var PermitItem = Form.GetString("PermitItem", "");
            foreach (var item in Employees)
            {
                var employeeCode = item["employeeCode"].ToString();
                var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == employeeCode);

                if (emp == null)
                {
                    
                }
                else
                {
                    emp.RealtionEmployeeCode = relationEmployeeCode;
                    emp.Roles = Role;
                    if (PermitItem != "")
                    {
                        emp.PermitItem = PermitItem;
                    }
                }
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult GetAccount()
        {
            var employeeCode = Form.GetString("employeeCode");
            var wx = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var account = ddService.listEmployeeAccountIds(employeeCode, wx.TenantId);
            if (account != null)
            {
                return this.ToJson(new
                {
                    success = true,
                    accountId = account["accountId"].ToString(),
                    accountCode = account["accountCode"].ToString(),
                });
            }
            return this.ToJson(new
            {
                success = false
            });
        }

        private (string UnitCode, string UnitName) GetUnit(string OrganizationCode)
        {
            var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
            if (org == null)
            {
                return ("", "");
            }
            if (org.TypeCode == "GOV_UNIT")
            {
                UnitCode = org.OrganizationCode;
                UnitName = org.Name;
            }
            if (org.TypeCode == "GOV_HOLLOW_STRIP_NODE")
            {
                return (UnitCode, UnitName);
            }
            return GetUnit(org.ParentCode);
        }

        public ActionResult SetState()
        {
            var Employees = Form.GetStringArray("Employees[]");
            var state = Form.GetInt("state");
            var user = ctx.Yqd_User.Where(it => Employees.Contains(it.EmployeeCode));
            foreach (var u in user)
            {
                u.Status = (用户状态)state;
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult UpdateAvatar()
        {
            var EmployeeCode = Form.GetString("EmployeeCode");
            var rootPath = Env.ServerRoot.Combine("wwwroot");
            var filepath = "/Client/Yqd/Avatar/";
            var path = rootPath + filepath;
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            var ret = 0;
            var user = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode);
            if (user != null)
            {
                var filename = user.EmployeeCode + ".jpg";
                var fpath = path + filename;
                if (System.IO.File.Exists(fpath)) System.IO.File.Delete(fpath);
                if (!string.IsNullOrWhiteSpace(user.Avatar))
                {
                    var bl = ddService.GenerateAvatar(user.Avatar, fpath);
                    ret = bl ? 1 : 0;
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult refresh()
        {
            var ParentCode = Form.GetString("OrganizationCode");
            var Paths = Form.GetString("Paths");
            var Fullname = Form.GetString("Fullname");

            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            List<string> arr = new List<string>();
            if (ParentCode.HasValue())
            {
                arr = ddService.pageSubOrganizationCodes(ParentCode, config.TenantId);
            }
            else
            {
                arr = ddService.scopesV2(config.TenantId)["deptVisibleScopes"].Select(it => it.ToString()).ToList();
            }
            var itemDeparts = ctx.Yqd_Department.Where(x => x.ParentCode == ParentCode).Select(x => x.OrganizationCode).ToList();
            if (itemDeparts.Any())
            {
                var result = itemDeparts.Except(arr).ToList();
                foreach (var item in result)
                {
                    var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == item);
                    if (org != null)
                    {
                        ctx.Yqd_Department.Remove(org);
                        ctx.SaveChanges();
                    }
                }
            }
            var r = new ArrayList();
            foreach (var item in arr)
            {
                var info = ddService.GetOrganizationInfo(item, config.TenantId);
                var isLeaf = ddService.pageSubOrganizationCodes(item, config.TenantId, true).Count == 0;
                var code = info["institutionLevelCode"]?.ToString() ?? "";
                var organizationCode = info["organizationCode"].ToString();
                var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == organizationCode);
                if (org == null)
                {
                    ctx.Yqd_Department.Add(new Yqd_Department
                    {
                        OrganizationCode = organizationCode,
                        ParentCode = ParentCode,
                        Name = info["organizationName"].ToString(),
                        InstitutionLevelCode = code,
                        InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code),
                        TypeCode = info["typeCode"]?.ToString() ?? "",
                        TypeName = info["typeName"]?.ToString() ?? "",
                        isLeaf = isLeaf

                    });
                }
                else
                {
                    org.Name = info["organizationName"].ToString();
                    org.InstitutionLevelCode = code;
                    org.InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code);
                    org.TypeCode = info["typeCode"]?.ToString() ?? "";
                    org.TypeName = info["typeName"]?.ToString() ?? "";
                    org.isLeaf = isLeaf;
                }
                ctx.SaveChanges();
            }
            var dep = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == ParentCode);
            return this.ToJson(new
            {
                success = true,
                parent = dep?.ParentCode,
                current = ParentCode
            });
        }
        public ActionResult GetRoleList()
        {
            var roles = new List<object>();
            var aroles = new List<object>();
            var types = typeof(角色类型);
            foreach (int item in Enum.GetValues(types))
            {
                if (item < (int)角色类型.督查管理员)
                    roles.Add(new { name = Enum.GetName(types, item), value = item.ToString() });
                else
                    aroles.Add(new { name = Enum.GetName(types, item), value = item.ToString() });
            }
            return this.ToJson(new
            {
                success = true,
                roles,
                aroles
            });
        }

        public ActionResult GetPermitList()
        {
            return this.ToJson(new
            {
                success = true,
                data = Enum.GetNames(typeof(权限清单)).Select(q => new
                {
                    value = Enum.Parse(typeof(权限清单), q),
                    name = q
                })
            });
        }

        public ActionResult GetClerkList()
        {
            var i = (int)角色类型.领导秘书;
            var users = ctx.Yqd_User.Where(it => it.AccountId > 0 && it.Status == 用户状态.使用中 && it.Roles.Contains(i.ToString())).ToList();

            return this.ToJson(new
            {
                success = true,
                data= users.Select(x=>new { 
                value = x.EmployeeCode,
                name=x.Name
                }).ToList()
            });
        }

        public ActionResult SetRelation()
        {
            var UnitID = Form.GetInt("UnitID");
            var OrgCode = Form.GetString("OrgCode");
            var ret = ctx.Database.ExecuteSql("update Yqd_Unit set OrganizationCode={1} where ID={0}", UnitID, OrgCode);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult UpdateDept()
        {
            var UnitCode = Form.GetString("DeptID");
            var empCode = Form.GetStringArray("empCode[]");
            var user = ctx.Yqd_User.Where(it => empCode.Contains(it.EmployeeCode));
            var dept = ctx.Yqd_Department.Where(x=>x.OrganizationCode == UnitCode).FirstOrDefault();
            foreach (var m in user)
            {
                m.UnitCode = UnitCode;
                if(dept != null)
                {
                    m.UnitName = dept.Name;
                }
                m.IsUpdateUnit = 1;
                m.updateDate = DateTime.Now;
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult Delete()
        {
            var Employees = Form.GetStringArray("Employees[]");
            var user = ctx.Yqd_User.Where(it => Employees.Contains(it.EmployeeCode));
            ctx.Yqd_User.RemoveRange(user);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
